from email.header import Header
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
import smtplib


def send_simple():
    msg = MIMEText("这是我使用python smtplib及email模块发送的邮件")
    msg['Subject'] = "python 普通文本"
    msg['From'] = from_addr
    msg['To'] = ';'.join(to_addr)
    return msg


def send_image():
    msgAlternative = MIMEMultipart('alternative')
    mail_msg = """
    <p>Python 邮件发送测试...</p>
    <p>图片演示：</p>
    <p><img src="cid:image1"></p>
    """
    msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))
    # 指定图片为当前目录
    fp = open('test.png', 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()

    # 定义图片 ID，在 HTML 文本中引用
    msgImage.add_header('Content-ID', '<image1>')
    msgAlternative.attach(msgImage)
    return msgAlternative


def send_html():
    msg = MIMEText('<a href="www.baidu.com">百度</a>', 'html', 'utf-8')
    msg['Subject'] = "python html邮件"
    msg['From'] = from_addr
    msg['To'] = ';'.join(to_addr)
    return msg


def send_fujian():
    # 创建一个带附件的实例
    message = MIMEMultipart()
    message['Subject'] = "python 带附件的"
    message['From'] = from_addr
    message['To'] = ';'.join(to_addr)

    # 邮件正文内容
    message.attach(MIMEText("正文内容", 'plain', 'utf-8'))

    # 构造附件（附件为txt格式的文本）
    att = MIMEText(open('send_email.py', 'rb').read(), 'base64', 'utf-8')
    att["Content-Type"] = 'application/octet-stream'
    att["Content-Disposition"] = 'attachment; filename="send_email.py"'
    message.attach(att)
    return message


if __name__ == '__main__':
    from_addr = '1335885004@qq.com'
    password = 'XXX'
    to_addr = ['XX@qq.com', 'XXXX@qq.com']
    smtp_server = 'smtp.qq.com'
    s = smtplib.SMTP_SSL("smtp.qq.com", 465)
    s.login(from_addr, password)
    msg = send_fujian()
    s.sendmail(from_addr, to_addr, msg.as_string())
    print("发送成功")
